import 'package:flutter/foundation.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:freedom/const/app_content.dart';

class VoiceMessageSound {
  VoiceMessageSound._();

  static VoiceMessageSound? _instance; // 静态变量

  static Uint8List? music;

  factory VoiceMessageSound() {
    _instance ??= VoiceMessageSound._();
    return _instance!;
  }

  void play(String code, {Function? close}) async {
    FlutterSoundPlayer audioPlayer = FlutterSoundPlayer();
    audioPlayer.openPlayer();
    int index =
        AppContent.MAHJONG_SOUND.indexWhere((audio) => audio.code == code);
    Uint8List? dataBuffer;
    if (index != -1) {
      dataBuffer = AppContent.MAHJONG_SOUND[index].audio;
    }
    if (dataBuffer == null) {
      audioPlayer.closePlayer();
      audioPlayer.dispositionStream();
    }
    audioPlayer.startPlayer(
        fromDataBuffer: dataBuffer,
        codec: Codec.mp3,
        whenFinished: () async {
          audioPlayer.closePlayer();
          audioPlayer.dispositionStream();
          if (close != null) {
            try {
              close();
            } catch (e) {
              if (kDebugMode) {
                print(e);
              }
            }
          }
        });
  }
}
